/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Gerente.Gerenciar;

import Controle.Controlador;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Andre Luiz
 */
public class GerenciarCategorias extends javax.swing.JFrame {

    ArrayList<ArrayList<String>> categorias;
    DefaultTableModel modelo;
    TableRowSorter sorter;

    /**
     * Creates new form GerenciarCategorias
     */
    public GerenciarCategorias() {
        initComponents();
        modelo = (DefaultTableModel) jtCategoria.getModel();
        sorter = new TableRowSorter(modelo);
        jScrollPane1.getViewport().setBackground(Color.WHITE);
        jtCategoria.getColumnModel().getColumn(0).setMinWidth(0);
        jtCategoria.getColumnModel().getColumn(0).setMaxWidth(0);
        jtCategoria.getColumnModel().getColumn(1).setPreferredWidth(200);
        jtCategoria.getColumnModel().getColumn(2).setPreferredWidth(100);
        jtCategoria.getColumnModel().getColumn(3).setPreferredWidth(100);
        categorias = imprimeDadosTabelas(carregarDadosBD());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtCategoria = new javax.swing.JTable();
        jbInserirCategoria = new javax.swing.JButton();
        jbEditarCategoria = new javax.swing.JButton();
        jbRemoverSabor = new javax.swing.JButton();
        jtfFiltro = new javax.swing.JTextField();
        jlFiltro = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Gerenciar Categorias");

        jtCategoria.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Categoria", "Tamanho", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtCategoria);

        jbInserirCategoria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/addCategoria.png"))); // NOI18N
        jbInserirCategoria.setToolTipText("Inserir uma nova Categoria");
        jbInserirCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbInserirCategoriaActionPerformed(evt);
            }
        });

        jbEditarCategoria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/EditarCategoria.png"))); // NOI18N
        jbEditarCategoria.setToolTipText("Editar Categoria");
        jbEditarCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbEditarCategoriaActionPerformed(evt);
            }
        });

        jbRemoverSabor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/delCategoria.png"))); // NOI18N
        jbRemoverSabor.setToolTipText("Remover Categoria");
        jbRemoverSabor.setPreferredSize(new java.awt.Dimension(64, 64));
        jbRemoverSabor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbRemoverSaborActionPerformed(evt);
            }
        });

        jtfFiltro.setToolTipText("Filtro de Busca");
        jtfFiltro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jtfFiltroKeyReleased(evt);
            }
        });

        jlFiltro.setText("Filtro:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jlFiltro)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtfFiltro))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jbEditarCategoria, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jbRemoverSabor, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbInserirCategoria, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtfFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlFiltro)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(79, 79, 79)
                        .addComponent(jbInserirCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbEditarCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbRemoverSabor, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 85, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void jbInserirCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbInserirCategoriaActionPerformed
        // Ao clicar no botão Inserir Sabor
        new InserirAlterarCategoria(this).setVisible(true);
    }//GEN-LAST:event_jbInserirCategoriaActionPerformed

    private void jbEditarCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbEditarCategoriaActionPerformed
        //Editar Caregoria
        try {
            int linha = jtCategoria.getSelectedRow();
            if (linha != -1) {
                int codigo = Integer.parseInt( jtCategoria.getValueAt(linha, 0).toString());
                InserirAlterarCategoria inserir = new InserirAlterarCategoria(this, codigo);
                inserir.setVisible(true);

            } else {
                throw new Exception("Selecione a linha da Categoria desejada");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Selecione a Categoria", 1);
        }
    }//GEN-LAST:event_jbEditarCategoriaActionPerformed

    private void jtfFiltroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfFiltroKeyReleased
        // Filtro:
        sorter.setRowFilter(RowFilter.regexFilter(jtfFiltro.getText().toUpperCase(), 1));
        jtCategoria.setRowSorter(sorter);
    }//GEN-LAST:event_jtfFiltroKeyReleased

    private void jbRemoverSaborActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRemoverSaborActionPerformed
        // Remover Caregoria
        try {
            int linha = jtCategoria.getSelectedRow();
            if (linha != -1) {
                int codigo = Integer.parseInt( jtCategoria.getValueAt(linha, 0).toString());
                int aux = JOptionPane.showConfirmDialog(this, "Deseja realmente remover a Categoria Selecionada? ", "Remover Categoria", 1, 3);
                if (aux == 0) {
                    Controlador.remover_Categoria(codigo);
                    atualizaTabela();
                }

            } else {
                throw new Exception("Selecione a linha da Categoria desejada");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jbRemoverSaborActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbEditarCategoria;
    private javax.swing.JButton jbInserirCategoria;
    private javax.swing.JButton jbRemoverSabor;
    private javax.swing.JLabel jlFiltro;
    private javax.swing.JTable jtCategoria;
    private javax.swing.JTextField jtfFiltro;
    // End of variables declaration//GEN-END:variables

    /**
     * Carrega todos os categorias do banco de dados
     *
     * @return Retorna uma lista de Sabores
     */
    private ArrayList<ArrayList<String>> carregarDadosBD() {
        return Controlador.carregarDadosBD_Categorias();
    }

    private ArrayList<ArrayList<String>> imprimeDadosTabelas(ArrayList<ArrayList<String>> categorias) {
        // Adiciona uma nova linha em branco no modelo  
        int linhaTabela = 0;
        jtCategoria.setRowSorter(null); // desabilita o filtro

        for (int i = 0; i < categorias.size(); i++) {
            try {
                if (jtCategoria.getRowCount() <= linhaTabela) {
                    modelo.addRow(new String[]{"", ""});
                }
                jtCategoria.setValueAt(categorias.get(i).get(0), linhaTabela, 0);
                jtCategoria.setValueAt(categorias.get(i).get(1), linhaTabela, 1);
                jtCategoria.setValueAt(categorias.get(i).get(2), linhaTabela, 2);
                jtCategoria.setValueAt(categorias.get(i).get(3), linhaTabela, 3);
            } catch (Exception ex) {
                System.out.println("Erro ao imprimir os dados na tabela\n" + ex.getMessage());
            }

            linhaTabela++;
        }
        removeLinhasInutilizadas(linhaTabela);
        jtfFiltroKeyReleased(null);
        return categorias;
    }

    public void removeLinhasInutilizadas(int linhaTabela) {
        for (int i = linhaTabela; i < jtCategoria.getRowCount(); i++) {
            modelo.removeRow(i);
        }
    }

    public void atualizaTabela() {
        imprimeDadosTabelas(carregarDadosBD());
    }
}
